package com.schoolET.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.schoolET.entity.AdminAndRegion;
import com.schoolET.entity.Administrators;
import com.schoolET.error.costom.AddRegionException;
import com.schoolET.mapper.AdminAndRegionMapper;
import com.schoolET.mapper.AdministratorsMapper;
import com.schoolET.service.IAdminAndRegionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 管理员和管理区域表 服务实现类
 * </p>
 *
 * @author le
 * @since 2024-06-01
 */
@Service
@Slf4j
public class AdminAndRegionServiceImpl extends ServiceImpl<AdminAndRegionMapper, AdminAndRegion> implements IAdminAndRegionService {

    @Resource
    private AdministratorsMapper administratorsMapper;


    @Override
    @Transactional
    public boolean addAdminAndRegion(AdminAndRegion adminAndRegion) {
        QueryWrapper<AdminAndRegion> wrapper =  new QueryWrapper<>();
        wrapper.eq("admin_id",adminAndRegion.getAdminId())
                .eq("region_id",adminAndRegion.getRegionId())
                .eq("flag",0);
        AdminAndRegion adminAndRegion1 = baseMapper.selectOne(wrapper);
        QueryWrapper<AdminAndRegion> wrapper1 =  new QueryWrapper<>();
        wrapper1.eq("region_id",adminAndRegion.getRegionId())
                .eq("flag",0);
        AdminAndRegion adminAndRegion3 = baseMapper.selectOne(wrapper1);
        if (adminAndRegion3 != null) {
            throw new AddRegionException();
        }
        if (adminAndRegion1 == null) {
            AdminAndRegion adminAndRegion2 = baseMapper.selectByAdminId(adminAndRegion.getAdminId());
            if (adminAndRegion2 != null) {
                baseMapper.deleteByAdminId(adminAndRegion2.getAdminId());
            }
            baseMapper.insert(adminAndRegion);
        } else {
            throw new AddRegionException();
        }
        return true;
    }

    @Override
    public Administrators selectByRegionId(Integer regionId) {
        AdminAndRegion adminAndRegion = baseMapper.selectByRegionId(regionId);
        log.info("adminAndRegion:{}",adminAndRegion);
        if (adminAndRegion == null) {
            return null;
        }
        return administratorsMapper.selectById(adminAndRegion.getAdminId());
    }
}
